<?php
header("Content-Type:text/html;charset=utf-8");
date_default_timezone_set("PRC");    
	define("TOKEN","weixin");
	if(!isset($_GET['echostr']))
	{
		//调用响应消息函数
		responseMsg();
	}
	else
	{
		//实现网址接入，调用验证消息函数	
		valid();
	}

	//验证消息
	function valid(){
		if(checkSignature())
		{
			$echostr = $_GET["echostr"];
			echo $echostr;
			exit;
		}
		else
		{
			echo "error";
			exit;
		}
	}

	//检查签名
	function checkSignature()
	{
		//获取微信服务器GET请求的4个参数
		$signature = $_GET['signature'];
		$timestamp = $_GET['timestamp'];
		$nonce = $_GET['nonce'];

		//定义一个数组，存储其中3个参数，分别是timestamp，nonce和token
		$tempArr = array($nonce,$timestamp,TOKEN);

		//进行排序
		sort($tempArr,SORT_STRING);

		//将数组转换成字符串

		$tmpStr = implode($tempArr);

		//进行sha1加密算法
		$tmpStr = sha1($tmpStr);

		//判断请求是否来自微信服务器，对比$tmpStr和$signature
		if($tmpStr == $signature)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	//响应消息
	function responseMsg(){
		//根据用户传过来的消息类型进行不同的响应
		//1、接收微信服务器POST过来的数据，XML数据包

		$postData = $GLOBALS[HTTP_RAW_POST_DATA];

		if(!$postData)
		{
			echo  "error";
			exit();
		}


		//2、解析XML数据包

	 	$object = simplexml_load_string($postData,"SimpleXMLElement",LIBXML_NOCDATA);
	 	//获取消息类型
	 	$MsgType = $object->MsgType;
       
	 	switch ($MsgType) {
	 		case 'event':
	 			receiveEvent($object);	
	 			break;	
	 		case 'text':
	 				//接收文本消息
	 	        echo receiveText($object);
	 			break;
            case 'location':
	 		        	//接收地理位置消息
	 		        	echo receiveLocation($object);
	 		default:
	 			break;
	 	}
	}
	//接收事件推送
	function receiveEvent($obj){
		switch ($obj->Event) {
			//关注事件
			case 'subscribe':
				//扫描带参数的二维码，用户未关注时，进行关注后的事件
				if(!empty($obj->EventKey)){
					//做相关处理
				}
				$contentStr = "欢迎关注武纺新生助手！想查看更多功能请回复‘帮助’。";
                echo replyText($obj,$contentStr);
				break;
			//取消关注事件
            case 'unsubscribe':        //取消关注后需要重新关注绑定
                $link=mysqli_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		        mysqli_select_db($link,"app_formtest1");
                mysqli_query($link,"UPDATE weixin_students SET student_weixin_id = 'NULL' WHERE student_weixin_id='$obj->FromUserName'");
				break;
			//自定义菜单事件
			case 'CLICK':
				
				switch ($obj->EventKey) {
					case '绑定通知书':
                    $kv = new SaeKV();
                    $ret = $kv->init();
                    $key = $obj->FromUserName;
                    $myinfo_inkvdb = $kv->get($key);
                    $link=mysqli_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		            mysqli_select_db($link,"app_formtest1");
                    $sql="select * from weixin_students where student_name='$myinfo_inkvdb'";
		            $r=mysqli_query($link,$sql);
                    $row=mysqli_fetch_object($r);
                    $student_weixin_id = $row->student_weixin_id;
                    if ($student_weixin_id==$obj->FromUserName){
                        $contentStr="你已经绑定,不能重复绑定！";
                        echo replyText($obj,$contentStr);
		          }
				      else {
                          $dataArray = array(
	 							array(
	 								"Title"=>"您还没有绑定，请点击绑定",
					                "Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/band.jpg",
					                "Url"=>"http://8.formtest1.sinaapp.com/callback1.php"
	 								)
				 				);
                          echo replyNews($obj,$dataArray); }
                        break;
                     case '个人信息':
                    $kv = new SaeKV();
                    $ret = $kv->init();
                    $key = $obj->FromUserName;
                    $myinfo_inkvdb = $kv->get($key);
                    $link=mysqli_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		            mysqli_select_db($link,"app_formtest1");
                    $sql="select * from weixin_students where student_name='$myinfo_inkvdb'";
		            $r=mysqli_query($link,$sql);
                    $row=mysqli_fetch_object($r);
                    $student_weixin_id = $row->student_weixin_id;
                    if ($student_weixin_id==$obj->FromUserName){
                        $dataArray = array(
	 							array(
	 								"Title"=>"个人信息",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/gerenxinxi.jpg",
	 								"Url"=>"http://8.formtest1.sinaapp.com/callback2.php"
	 								),
				 				);
                          echo replyNews($obj,$dataArray);
                       
		          }
				      else {
                    	  $dataArray = array(
	 							array(
	 								"Title"=>"查看个人信息请先绑定",
					                "Description"=>"",
					                "Url"=>"http://8.formtest1.sinaapp.com/callback1.php"
	 								)
				 				);
                          echo replyNews($obj,$dataArray);}
                    
						break;
                     case '学校简介':
                    $kv = new SaeKV();
                    $ret = $kv->init();
                    $key = $obj->FromUserName;
                    $myinfo_inkvdb = $kv->get($key);
                    $link=mysqli_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		            mysqli_select_db($link,"app_formtest1");
                    $sql="select * from weixin_students where student_name='$myinfo_inkvdb'";
		            $r=mysqli_query($link,$sql);
                    $row=mysqli_fetch_object($r);
                    $student_weixin_id = $row->student_weixin_id;
                    if ($student_weixin_id==$obj->FromUserName){
                    	$dataArray = array(
	 							array(
	 								"Title"=>"学校简介",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/xuexiaojianjie.jpg",
                                    //"Url"=>"http://wuhanfangzhida.flzhan.com"
                                    "Url"=>"http://v.xiumi.us/board/v5/20M0G/5313136"
	 								),
				 				);
                    
            	echo replyNews($obj,$dataArray);
                         
		          }
				      else {
                    	 $dataArray = array(
	 							array(
	 								"Title"=>"查看学校简介请先绑定",
					                "Description"=>"",
					                "Url"=>"http://8.formtest1.sinaapp.com/callback1.php"
	 								)
				 				);
                          echo replyNews($obj,$dataArray);}
						break;
                    case '学院简介':
                    $kv = new SaeKV();
                    $ret = $kv->init();
                    $key = $obj->FromUserName;
                    $myinfo_inkvdb = $kv->get($key);
                    $link=mysqli_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		            mysqli_select_db($link,"app_formtest1");
                    $sql="select * from weixin_students where student_name='$myinfo_inkvdb'";
		            $r=mysqli_query($link,$sql);
                    $row=mysqli_fetch_object($r);
                    $student_weixin_id = $row->student_weixin_id;
                    if ($student_weixin_id==$obj->FromUserName){
                    	$dataArray = array(
	 							array(
	 								"Title"=>"学院简介",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/xueyuanjianjie.jpg",
	 								"Url"=>"http://8.formtest1.sinaapp.com/callback.php"
	 								),
				 				);
                     
            	echo replyNews($obj,$dataArray);
                    }
				      else {
                    	 $dataArray = array(
	 							array(
	 								"Title"=>"查看学院简介请先绑定",
					                "Description"=>"",
					                "Url"=>"http://8.formtest1.sinaapp.com/callback1.php"
	 								)
				 				);
                          echo replyNews($obj,$dataArray);}
						break;
                    case '校园导航':
                    $kv = new SaeKV();
                    $ret = $kv->init();
                    $key = $obj->FromUserName;
                    $myinfo_inkvdb = $kv->get($key);
                    $link=mysqli_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		            mysqli_select_db($link,"app_formtest1");
                    $sql="select * from weixin_students where student_name='$myinfo_inkvdb'";
		            $r=mysqli_query($link,$sql);
                    $row=mysqli_fetch_object($r);
                    $student_weixin_id = $row->student_weixin_id;
                    if ($student_weixin_id==$obj->FromUserName){
                    $dataArray = array();
                    	$dataArray[] = array(
	 								"Title"=>"校园导航",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/xiaoyuandaohang.jpg",
                                    //"Url"=>"http://map.baidu.com/mobile/"
                                    "Url"=>"http://1.formtest1.sinaapp.com/map2.php"
				 				);
                     
                    $dataArray[] = array(
	 								"Title"=>"查询地图",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/mapchaxun.jpg",
                                    //"Url"=>"http://map.baidu.com/mobile/"
                                    "Url"=>"http://map.baidu.com/mobile/webapp/index/index/foo=bar/tab=line"
				 				);
                    $dataArray[] = array(
	 								"Title"=>"查询公交",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/buschaxun.jpg",
                                    //"Url"=>"http://map.baidu.com/mobile/"
                                    "Url"=>"http://map.baidu.com/mobile/webapp/third/transit/"
				 				);
                     
            	echo replyNews($obj,$dataArray);
                     }
				      else {
                    	 $dataArray = array(
	 							array(
	 								"Title"=>"查看校园导航请先绑定",
					                "Description"=>"",
					                "Url"=>"http://8.formtest1.sinaapp.com/callback1.php"
	 								)
				 				);
                          echo replyNews($obj,$dataArray);}
						break;
                    case '入学路线指南':
                    $kv = new SaeKV();
                    $ret = $kv->init();
                    $key = $obj->FromUserName;
                    $myinfo_inkvdb = $kv->get($key);
                    $link=mysqli_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		            mysqli_select_db($link,"app_formtest1");
                    $sql="select * from weixin_students where student_name='$myinfo_inkvdb'";
		            $r=mysqli_query($link,$sql);
                    $row=mysqli_fetch_object($r);
                    $student_weixin_id = $row->student_weixin_id;
                    if ($student_weixin_id==$obj->FromUserName){
                    	$dataArray = array(
	 							array(
	 								"Title"=>"入学路线指南",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/ruxueluxian.jpg",
	 								"Url"=>"http://8.formtest1.sinaapp.com/route.php"
	 								),
				 				);
                   
            	echo replyNews($obj,$dataArray);
                   }
				      else {
                    	 $dataArray = array(
	 							array(
	 								"Title"=>"查看入学路线指南请先绑定",
					                "Description"=>"",
					                "Url"=>"http://8.formtest1.sinaapp.com/callback1.php"
	 								)
				 				);
                          echo replyNews($obj,$dataArray);}
						break;
                    case '校园社区':
                    $kv = new SaeKV();
                    $ret = $kv->init();
                    $key = $obj->FromUserName;
                    $myinfo_inkvdb = $kv->get($key);
                    $link=mysqli_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		            mysqli_select_db($link,"app_formtest1");
                    $sql="select * from weixin_students where student_name='$myinfo_inkvdb'";
		            $r=mysqli_query($link,$sql);
                    $row=mysqli_fetch_object($r);
                    $student_weixin_id = $row->student_weixin_id;
                    if ($student_weixin_id==$obj->FromUserName){
                    	$dataArray = array(	 							
                        array(
	 								"Title"=>"校园社区",
					                "Description"=>"",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/xiaoyuanshequ.jpg",
					                "Url"=>"http://8.formtest1.sinaapp.com/bbs/test.php"
	 								)
				 				);
                    
            	echo replyNews($obj,$dataArray);
                     }
				      else {
                    	 $dataArray = array(
	 							array(
	 								"Title"=>"您还没有绑定，请点击绑定",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/band.jpg",
	 								"Url"=>"http://8.formtest1.sinaapp.com/callback1.php"
                                    ),
				 				);
                          echo replyNews($obj,$dataArray);}
						break;
					default:
						break;
				}
				break;
		}	
	}

	//接收文本消息
	function receiveText($object){       
        $mem = memcache_init();
        $keyword = trim($object->Content);
        if (strstr($keyword, "帮助")){
             echo replyText($object, "回复1或者绑定：绑定通知书;\n回复2或者个人信息: 查看个人信息;\n回复城市名加天气可以查询天气;\n若要查询附近请先发送位置给我！\n点击底部的‘+’号，再选择‘位置’，等地图显示出来以后，点击‘发送’");
         }
        else if (strstr($keyword, "1") || strstr($keyword, "绑定")){
             echo replyText($object, "<a href=\"http://8.formtest1.sinaapp.com/callback1.php\">绑定通知书</a>");
         }
        else if (strstr($keyword, "2") || strstr($keyword, "个人信息")){
             echo replyText($object, "<a href=\"http://8.formtest1.sinaapp.com/callback2.php\">个人信息</a>");
         }
        /* else if (strstr($keyword, "天气")){
             $dataArray = array(
	 							array(
	 								"Title"=>"天气预报",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/weather.jpg",
	 								"Url"=>"http://8.formtest1.sinaapp.com/callback4.php"
	 								),
				 				);
                     
            	echo replyNews($object,$dataArray);
         }*/
        else if (strstr($keyword, "附近")){
            $locat = $object->FromUserName;
            $location=$mem->get($locat,$Arrayxy);
            if(!empty($location))
            {
            $query = substr($object->Content,6);
            $arr1 = array("query"=>$query);
            array_splice($location,2,1,$arr1);          //array_splice选择数组中的一系列元素，但不返回，而是删除它们并用其它值代替
            $arr2 = $mem->set($locat,$location,0,600);
            $url = "http://api.map.baidu.com/place/v2/search?ak=j8ywPTMtTmYACru9r20R4tVb&output=json&query={$query}&page_size=5&page_num=0&scope=2&location={$location['lng']},{$location['lat']}&radius=2000&filter=sort_name:distance";
        $r = file_get_contents($url);
        $l = json_decode($r);         
                $dataArray = array();
                $dataArray[] = array(
                                    "Title"=>"附近的【".$query."】如下：",
	 								"Description"=>"this is a test",
                                    "PicUrl"=>"http://8.formtest1.sinaapp.com/img/xiaoyuandaohang.jpg",
                                    "Url"=>"http://8.formtest1.sinaapp.com/callback3.php"
				 				);
                //$searchArray = array(); 
                /*
                //周平平写
                */
                $dataArray[] = array(
	 								"Title"=>$l->results[0]->name.$l->results[0]->address.$l->results[0]->telephone,
                                    "Description"=>"",
                                    "Url"=>"http://api.map.baidu.com/direction?origin=latlng:{$location['lng']},{$location['lat']}|name:我的位置&destination={$l->results[0]->location->lat},{$l->results[0]->location->lng}&mode=walking&region=武汉&output=html&src=yourCompanyName|yourAppName"
            );
                $dataArray[] = array(
	 								"Title"=>$l->results[1]->name.$l->results[1]->address.$l->results[1]->telephone,
	 								"Description"=>"",
                                    "Url"=>"http://api.map.baidu.com/direction?origin=latlng:{$location['lng']},{$location['lat']}|name:我的位置&destination={$l->results[1]->location->lat},{$l->results[1]->location->lng}&mode=walking&region=武汉&output=html&src=yourCompanyName|yourAppName"
				 				);
        $dataArray[] = array(
	 								"Title"=>$l->results[2]->name.$l->results[2]->address.$l->results[2]->telephone,
	 								"Description"=>"",
                                    "Url"=>"http://api.map.baidu.com/direction?origin=latlng:{$location['lng']},{$location['lat']}|name:我的位置&destination={$l->results[2]->location->lat},{$l->results[2]->location->lng}&mode=walking&region=武汉&output=html&src=yourCompanyName|yourAppName"
                );
                		 				
        $dataArray[] = array(
	 								"Title"=>$l->results[3]->name.$l->results[3]->address.$l->results[3]->telephone,
	 								"Description"=>"",
                                    "Url"=>"http://api.map.baidu.com/direction?origin=latlng:{$location['lng']},{$location['lat']}|name:我的位置&destination={$l->results[3]->location->lat},{$l->results[3]->location->lng}&mode=walking&region=武汉&output=html&src=yourCompanyName|yourAppName"
                );
                		 				
        $dataArray[] = array(
	 								"Title"=>$l->results[4]->name.$l->results[4]->address.$l->results[4]->telephone,
	 								"Description"=>"",
                                    "Url"=>"http://api.map.baidu.com/direction?origin=latlng:{$location['lng']},{$location['lat']}|name:我的位置&destination={$l->results[4]->location->lat},{$l->results[4]->location->lng}&mode=walking&region=武汉&output=html&src=yourCompanyName|yourAppName"
                );
                     
                return replyNews($object,$dataArray);
            /*for ($i = 0; $i < count($l->results); $i++) {
        $shopSortArrays[] = array(
            "Title"=>$l->results[$i]->name.$l->results[$i]->address.$l->results[$i]->telephone,
            "Description"=>"", 
            "Url"=>"");
                }
        //ksort($shopSortArrays);//排序
    $shopArray = array(); 
    foreach ($shopSortArrays as $key => $value) {  
        $shopArray[] =  array(
                        "Title" => $value["Title"],
                        "Description" => $value["Description"],
                        "Url" => $value["Url"],
                    );
        return replyNews($obj,array_merge_recursive($TitleArray,$ShopArray));
        if (count($shopArray) > 6){break;}
         }*/
            }
            else{
                return replyText($object,"请重新发送您的位置。缓存之后发送“附近”加目标的命令，如“附近酒店”，“附近银行”。");
            }
            $mem->close;
         }
        else {
        $link=mysqli_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		mysqli_select_db($link,"app_formtest1");
        $FromUserName = $object->FromUserName;
        $Content = $object->Content;
            //$Time = $object->CreateTime;
        
        $AddTime = date('y-m-d h:i:s',time());
        //拼装添加sql语句
		$sql = "insert into wx_message values(null,'$FromUserName','$Content','$AddTime')"; 
		//执行添加操作
		mysqli_query($link,$sql);
          
        echo replyText($object, ichat($keyword));
         }
	}
	
	//接收地理位置消息
	function receiveLocation($obj)
	{
        $mem = memcache_init();
		//获取地理位置消息的内容
		$locationArr = array(
				"Location_X"=>$obj->Location_X,
				"Location_Y"=>$obj->Location_Y,
				"Label"=>$obj->Label
			);
		//return replyText($obj,$locationArr['Location_Y']);
        $lat = $obj->Location_X;  //纬度
        $lng = $obj->Location_Y;  //经度
        $q = "http://api.map.baidu.com/geoconv/v1/?coords={$lng},{$lat}&from=1&to=5&ak=j8ywPTMtTmYACru9r20R4tVb";
        $result = json_decode(file_get_contents($q));
        //echo replyText($obj, "转换前".$obj->Location_X."\n"."转换前".$obj->Location_Y."\n"."转换后".$result->result[0]->x."\n"."转换后".$result->result[0]->y);
        $Arrayxy = array("lat"=>$result->result[0]->x,"lng"=>$result->result[0]->y,"query"=>"位置");
        $locat = $obj->FromUserName;
        $mem->set($locat, $Arrayxy, 0, 600);
        return replyText($obj,"您的位置已缓存。\n现在可发送“附近”加目标的命令，如“附近酒店”，“附近加油站”。");
        $mem->close;        
	}

	

	//发送文本消息
	function replyText($obj,$content){
		$replyXml = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[text]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					</xml>";
	        //返回一个进行xml数据包

		$resultStr = sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time(),$content);
        
	        return $resultStr;		
	}

	//回复图文消息
	function replyNews($obj,$newsArr){
		$itemStr = "";
		if(is_array($newsArr))
		{
			foreach($newsArr as $item)
			{
				$itemXml ="<item>
					<Title><![CDATA[%s]]></Title> 
					<Description><![CDATA[%s]]></Description>
					<PicUrl><![CDATA[%s]]></PicUrl>
					<Url><![CDATA[%s]]></Url>
					</item>";
				$itemStr .= sprintf($itemXml,$item['Title'],$item['Description'],$item['PicUrl'],$item['Url']);
			}

		}

		$replyXml = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<ArticleCount>%s</ArticleCount>
					<Articles>
						{$itemStr}
					</Articles>
					</xml> ";
	        //返回一个进行xml数据包

		$resultStr = sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time(),count($newsArr));
	        return $resultStr;			
    }
//图灵智能聊天机器人接口
     function ichat($keyword){

        $key="76519f667e19c49d93d534a3ec415d7d";
        $url="http://www.tuling123.com/openapi/api?key={$key}&info=".$keyword;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);

        $message = json_decode($output,true);
        $response = $message['text'];
        
         //防止机器人服务器异常回复自定义消息 
        if(!empty($response)){
            return $response;
        }else{
            $ran=rand(1,5);
            switch($ran){
                case 1:
                    return "胡巴今天累了，明天再陪你聊天吧。";
                    break;
                case 2:
                    return "胡巴睡觉喽~~";
                    break;
                case 3:
                    return "呼呼~~呼呼~~";
                    break;
                case 4:
                    return "你话好多啊，不跟你聊了";
                    break;
                case 5:
                    return "感谢您关注【武纺新生助手】";
                    break;
                default:
                    return "感谢您关注【武纺新生助手】";
                    break;
            }
        }
    }
?>